﻿using CommunityToolkit.Mvvm.Input;
using DataChangeTools.Events;
using DataChangeTools.Models;
using DryIoc.ImTools;
using MaterialDesignThemes.Wpf;
using Newtonsoft.Json;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace DataChangeTools.ViewModel
{
    public class BatchRenameWithImageViewModel : BindableBase
    {


        private System.Timers.Timer _timer;
        #region 字段
        private string filePath;
        public string FilePath
        {
            get { return filePath; }
            set => SetProperty(ref filePath, value);
            // 自动触发属性变更通知
        }
        private int totalCount;

        public int TotalCount
        {
            get { return totalCount; }
            set => SetProperty(ref totalCount, value); // 自动触发属性变更通知
        }

        private int dealCount;

        public int DealCount
        {
            get { return dealCount; }
            set => SetProperty(ref dealCount, value); // 自动触发属性变更通知
        }
        private int notDealCount;

        public int NotDealCount
        {
            get { return notDealCount; }
            set => SetProperty(ref notDealCount, value); // 自动触发属性变更通知
        }
        private bool isInit;

        public bool IsInit
        {
            get { return isInit; }
            set => SetProperty(ref isInit, value); // 自动触发属性变更通知
        }

        private ObservableCollection<BatchRenameModel> batchRenameList;

        public ObservableCollection<BatchRenameModel> BatchRenameList
        {
            get { return batchRenameList; }
            set
            {

                if (batchRenameList != null)
                    batchRenameList.CollectionChanged -= BatchRenameList_CollectionChanged;
                SetProperty(ref batchRenameList, value);
                if (batchRenameList != null)
                    batchRenameList.CollectionChanged += BatchRenameList_CollectionChanged;


            } // 自动触发属性变更通知
        }

        private void BatchRenameList_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.OldItems != null)
            {
                foreach (BatchRenameModel item in e.OldItems)
                    item.PropertyChanged += Item_PropertyChanged;
            }
            if (e.NewItems != null)
            {
                foreach (BatchRenameModel item in e.NewItems)
                    item.PropertyChanged += Item_PropertyChanged;
            }
        }

        private void Item_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(BatchRenameModel.State))
            {
                UpdateCounts();
            }
        }

        private void UpdateCounts()
        {
            int deal = 0;
            foreach (var item in BatchRenameList)
            {
                if (item.State == 1)
                {
                    deal++;
                    if (IsInit && DealCount <= 0)
                    {
                        InItTimer();
                    }
                    IsInit = false;

                }

            }
            DealCount = deal;
            NotDealCount = TotalCount - deal;
        }

        #endregion



        //负责执行不同的模块
        public DelegateCommand<Button> ChooseFilesCmd { get; private set; }
        public DelegateCommand<Button> LoadFilesCmd { get; private set; }
        public DelegateCommand<Button> SaveFilesCmd { get; private set; }
        public DelegateCommand<Button> LoadSavedFilesCmd { get; private set; }
        public DelegateCommand<Button> RestoreSavedFilesCmd { get; private set; }

        public DelegateCommand<TextBox> HandleKeyDownCommand { get; private set; }



        public DelegateCommand<System.Windows.Controls.Image> MouseEnterCommand { get; private set; }
        public DelegateCommand<System.Windows.Controls.Image> MouseDownCommand { get; private set; }
        public DelegateCommand<System.Windows.Controls.Image> MouseLeaveCommand { get; private set; }

        public DelegateCommand<System.Windows.Controls.Image> MouseMoveCommand { get; private set; }


        private readonly IEventAggregator _eventAggregator;

        public BatchRenameWithImageViewModel(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;

            BatchRenameList = new ObservableCollection<BatchRenameModel>();
            ChooseFilesCmd = new DelegateCommand<Button>(ChooseFiles);
            LoadFilesCmd = new DelegateCommand<Button>(LoadFiles);
            SaveFilesCmd = new DelegateCommand<Button>(SaveFiles);
            LoadSavedFilesCmd = new DelegateCommand<Button>(LoadSavedFiles);
            RestoreSavedFilesCmd = new DelegateCommand<Button>(RestoreSavedFiles);
            HandleKeyDownCommand = new DelegateCommand<TextBox>(HandleKeyDown);

            MouseEnterCommand = new DelegateCommand<System.Windows.Controls.Image>(MouseEnter_Image);
            MouseLeaveCommand = new DelegateCommand<System.Windows.Controls.Image>(MouseLeave_Image);
            MouseMoveCommand = new DelegateCommand<System.Windows.Controls.Image>(MouseMove_Image);

            MouseDownCommand = new DelegateCommand<System.Windows.Controls.Image>(MouseDown_Image);



            InItData();
        }

        private void MouseDown_Image(System.Windows.Controls.Image img)
        {
            HandyControl.Controls.PopupWindow popupWindow = new HandyControl.Controls.PopupWindow();
            popupWindow.ShowDialog(img, false); // 使用 ShowDialog() 使弹出窗口为模态窗口
        }
        private void MouseMove_Image(System.Windows.Controls.Image img)
        {

        }
        private void MouseEnter_Image(System.Windows.Controls.Image img)
        {
            //MagnifierCircle.Visibility = Visibility.Visible;
        }
        private void MouseLeave_Image(System.Windows.Controls.Image img)
        {
            //MagnifierCircle.Visibility = Visibility.Hidden;
        }

        private void HandleKeyDown(TextBox textBox)
        {
            if (Keyboard.IsKeyDown(Key.Tab))
            {
                // 如果需要，在此处添加业务逻辑
            }
        }
        private void InItData()
        {
            IsInit = true;
            //判断当前是否存在auto_save.json文件
            string AutoFilePath = $"{GetProjectRootPath()}\\auto_save\\auto_save.json";

            if (File.Exists(AutoFilePath))
            {
                var packet = new FileInfo(AutoFilePath);
                //提示是否加载已有数据
                var dr = HandyControl.Controls.MessageBox.Show(
                    $"是否还原上次保存的数据\n保存时间：{packet.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")}", "是否加载",
                    MessageBoxButton.OKCancel, MessageBoxImage.Question);
                //存在不启动Timer

                if (dr == MessageBoxResult.OK)
                {
                    ReLoadDataByJsonFile();
                }


            }
        }

        private void InItTimer()
        {
            // 初始化定时器，设置间隔时间为 5 分钟（300000 毫秒）
            _timer = new System.Timers.Timer(3 * 1000 * 30);
            _timer.Elapsed += OnTimedEvent;
            _timer.AutoReset = true;
            _timer.Enabled = true;
        }





        private void ChooseFiles(Button obj)
        {
            //打开文件选择
            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
            folderBrowserDialog.ShowDialog();        //这个方法可以显示文件夹选择对话框
            string directoryPath = folderBrowserDialog.SelectedPath;    //获取选择的文件夹的全路径名
            FilePath = directoryPath;
        }

        private void RestoreSavedFiles(Button obj)
        {
            ReLoadDataByJsonFile();
            //LoadListViewData(List);
        }

        private void ReLoadDataByJsonFile()
        {
            BatchRenameList = new ObservableCollection<BatchRenameModel>();
            string directoryPath = Path.GetDirectoryName(GetProjectRootPath() + $"\\auto_save\\");
            var FullPath = directoryPath + $"\\auto_save.json";
            if (!File.Exists(FullPath))
            {
                PostGrowlEvent("当前没有任何自动备份，请修改", Events.EnumAlarmType.Fatal);
                return;
            }
            //读取文字到string
            var content = File.ReadAllText(FullPath);

            //加载内容
            var List = JsonConvert.DeserializeObject<ObservableCollection<BatchRenameModel>>(content);
            BatchRenameList.AddRange(List);
            TotalCount = List.Count();
            //获取第一个
            var ListItem = List.FirstOrDefault();
            if (ListItem != null)
            {
                var dir = new DirectoryInfo(ListItem.Image);
                FilePath = dir.Parent.FullName;
            }

        }


        private void LoadSavedFiles(Button obj)
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                //MessageBox.Show("未选择文件夹，请前往选择！");
                PostGrowlEvent("未选择文件夹，请前往选择！", Events.EnumAlarmType.Fatal);
                return;
            }
            DirectoryInfo directoryInfo = new DirectoryInfo(FilePath);
            var NewDir = directoryInfo.Parent + "\\RenameData\\";
            LoadListViewData(NewDir, true);
        }
        private void SaveFiles(Button obj)
        {
            var SaveSuccess = 0;
            var SaveFail = 0;
            //复制文件到新目录，并且重名文件
            DirectoryInfo directoryInfo = new DirectoryInfo(FilePath);
            var NewDir = directoryInfo.Parent + "\\RenameData\\";

            if (BatchRenameList == null)
            {
                PostGrowlEvent("未加载文件列表，请前往加载！", Events.EnumAlarmType.Fatal);
                return;
            }
            //保存數據为Json
            SaveToJSON(BatchRenameList);

            var List = BatchRenameList.Where(t => !string.IsNullOrWhiteSpace(t.Code));
            foreach (var item in List)
            {
                var newFileName = item.Code + item.FileName;
                // 组合目标文件路径
                string destinationFilePath = Path.Combine(NewDir, newFileName);
                try
                {
                    // 检查目标文件夹是否存在，如果不存在则创建
                    if (!Directory.Exists(NewDir))
                    {
                        Directory.CreateDirectory(NewDir);
                    }
                    // 复制文件并重命名
                    File.Copy(item.Image, destinationFilePath, overwrite: true);
                    SaveSuccess++;
                }
                catch (Exception ex)
                {
                    SaveFail++;
                    continue;
                }
            }
            PostGrowlEvent($"操作成功！成功：{SaveSuccess}失败：{SaveFail}", Events.EnumAlarmType.Info);
        }


        private void LoadFiles(Button obj)
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                // MessageBox.Show("未选择文件夹，请前往选择！");
                PostGrowlEvent("未选择文件夹，请前往选择！", Events.EnumAlarmType.Fatal);
                return;
            }
            LoadListViewData(FilePath);
        }

        private void LoadListViewData(string FilePath, bool LoadSaved = false)
        {
            BatchRenameList = new ObservableCollection<BatchRenameModel>();
            //给页面赋值
            List<string> files = new List<string>(Directory.GetFiles(FilePath, "*.*", SearchOption.AllDirectories));
            TotalCount = files.Count;
            //NotDealCount = TotalCount - DealCount;
            for (var i = 0; i < files.Count; i++)
            {
                //D:\pycharmProject\DownloadCodeImg/RenameData/1_1738461794.833168.png
                //判断当前目录的父级的Reanme 是否存在同样时间戳文件
                var fileName = files[i].Split('\\')[4];
                var code = "";
                var state = 0;
                if (LoadSaved)
                {
                    var NameArray = fileName.Split("_").ToArray();
                    fileName = "_" + NameArray[1];
                    code = NameArray[0];
                    state = 1;
                }
                else
                {
                    var HasData = GetAllFile().Where(t => t.Contains(fileName)).FirstOrDefault();
                    if (HasData != null)
                    {
                        continue;
                    }
                }

                BatchRenameList.Add(new BatchRenameModel
                {
                    Id = $"{i}",
                    FileName = fileName,
                    Code = code,
                    State = state,
                    Image = files[i]
                });
            }
        }


        private List<string> GetAllFile()
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(FilePath);
            var NewDir = directoryInfo.Parent + "\\RenameData\\";

            List<string> files = new List<string>(Directory.GetFiles(NewDir, "*.*", SearchOption.AllDirectories));

            return files;
        }
        private void SaveToJSON(ObservableCollection<BatchRenameModel> List)
        {
            string JsonData = JsonConvert.SerializeObject(BatchRenameList);
            //项目的根目录

            //File.WriteAllText(GetProjectRootPath()+"\\Jsondata.json", JsonData);
            // 将 JSON 字符串转换为字节数组
            byte[] jsonBytes = Encoding.UTF8.GetBytes(JsonData);

            string directoryPath = Path.GetDirectoryName(GetProjectRootPath() + $"\\back\\{DateTime.Now.ToString("yyyMMdd")}\\");
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            // 将字节数组写入 .dat 文件
            File.WriteAllBytes(directoryPath + $"\\{DateTime.Now.ToString("HHmmss")}.dat", jsonBytes);
        }

        public static string GetProjectRootPath()
        {
            // 获取当前执行程序的位置
            string executablePath = Assembly.GetExecutingAssembly().Location;
            // 获取程序所在目录
            string directoryPath = Path.GetDirectoryName(executablePath);
            return directoryPath;
        }

        private void AutoSaveData()
        {
            string JsonData = JsonConvert.SerializeObject(BatchRenameList);
            //项目的根目录
            string directoryPath = Path.GetDirectoryName(GetProjectRootPath() + $"\\auto_save\\");
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            // 将字节数组写入 .dat 文件
            File.WriteAllText(directoryPath + $"\\auto_save.json", JsonData);
        }

        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            // 定时器触发时保存数据
            AutoSaveData();
        }


        void PostGrowlEvent(string strMessage, EnumAlarmType enumat)
        {
            //HandyControl.Controls.Growl.Error(strMessage);
            _eventAggregator.GetEvent<GrowlEvent>().Publish(new GrowMsg()
            {
                enumAlarmType = enumat,
                message = strMessage,
            });
        }
    }

}
